﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace TesteSiteDataQuery
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable tablewebs = new DataTable();
            tablewebs.Columns.Add("name", typeof(string));
            tablewebs.Columns.Add("value", typeof(string));

            DataRow row1 = tablewebs.NewRow();
            row1["name"] = "SiteColecction";
            row1["value"] = "<Webs Scope='SiteCollection' />";
            tablewebs.Rows.Add(row1);
            DataRow row2 = tablewebs.NewRow();
            row2["name"] = "Site Recursive";
            row2["value"] = "<Webs Scope='Recursive' />";
            tablewebs.Rows.Add(row2);


                comboBox1.ValueMember = "value";
                comboBox1.DisplayMember = "name";
                comboBox1.DataSource = tablewebs;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Enabled = false;
                Cursor.Current = Cursors.WaitCursor;

                if (string.IsNullOrEmpty(textBox1.Text))
                    throw new Exception("Tem de preencher o URl");
          
                if (string.IsNullOrEmpty(richTextBox1.Text))
                    throw new Exception("Tem de preencher a Query");

                SPSite site = new SPSite(textBox1.Text);
                SPWeb web = site.OpenWeb();

                SPSiteDataQuery sitequery = new SPSiteDataQuery();
                sitequery.Webs = comboBox1.SelectedValue.ToString();
                sitequery.Lists = "<Lists ServerTemplate='850'/>";
               
                sitequery.Query = richTextBox1.Text.Replace("\\n|\\r", " ");
                sitequery.ViewFields = richTextBox2.Text;

                dataGridView1.DataSource = web.GetSiteData(sitequery);

                web.Dispose();
                label1.Text = "Resultados: " + dataGridView1.RowCount;

                Enabled = true;
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message; 
                Enabled = true;
                Cursor.Current = Cursors.Default;
            }
        }
    }
}
